package cn.rui.service;

import cn.rui.aop.Log;
import cn.rui.mapper.SyLogMapper;
import cn.rui.pojo.SysLog;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 徽州大都督
 * @date 2020/8/13
 */
@Service
public class SyLogService {

    @Autowired
    private SyLogMapper syLogMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 保存日志,每天晚上12点从缓存导入数据库
     *
     * @param sysLog
     */
    public void addLog(SysLog sysLog) {

        if (redisTemplate.opsForValue ().get ("logList") == null) {
            List<SysLog> logList = new ArrayList<> ();
            logList.add (sysLog);
            redisTemplate.opsForValue ().set ("logList", logList);
        } else {
            List<SysLog> sysLogs = (List<SysLog>) redisTemplate.opsForValue ().get ("logList");
            sysLogs.add (sysLog);
            redisTemplate.opsForValue ().set ("logList", sysLogs);
        }
        //syLogMapper.insert (sysLog);
    }


    /**
     * 保存日志到数据库
     *
     * @param sysLog
     */
    public void addLogs(SysLog sysLog) {


        syLogMapper.insert (sysLog);
    }

    /**
     * 分页查询日志
     *
     * @param page
     * @param size
     * @return
     */
    public List<SysLog> findByPage(int page, int size) {
        Page<SysLog> page1 = new Page<> (page, size);

        IPage<SysLog> sysLogIPage = syLogMapper.selectPage (page1, null);
        long total = sysLogIPage.getTotal ();
        List<SysLog> sysLogList = sysLogIPage.getRecords ();
        for (SysLog sysLog : sysLogList) {
            sysLog.setTotal (total);
        }

        return sysLogList;
    }

    /**
     * 查询全部日志
     */
    public List<SysLog> findAll() {
        List<SysLog> logList = syLogMapper.selectList (null);
        return logList;

    }

    /**
     * 删除100条靠前的日志
     */
    public void delete() {

        Page<SysLog> page =new Page<> (1,100);
        QueryWrapper<SysLog> wrapper = new QueryWrapper<> ();
        wrapper.orderByAsc ("id");  //升序
        IPage<SysLog> iPage = syLogMapper.selectPage (page, wrapper);
        List<SysLog> logs = iPage.getRecords ();

        for (SysLog log : logs) {
            syLogMapper.deleteById (log.getId ());
        }
    }
}
